package multithreading;

/**
 * 0-100 交替线程出现
 *
 * @author DuJiabao
 * @create 2020-12-13 21:45
 */
public class Alternate {
    public static void main(String[] args) {
        NumberAlternate numberAlternate = new NumberAlternate();
        Thread thread1 = new Thread(numberAlternate);
        Thread thread2 = new Thread(numberAlternate);

        thread1.start();
        thread2.start();
    }
}

class NumberAlternate implements Runnable {
    private int i = 0;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                //唤醒一个线程
                notify();
                if (i <= 100) {
                    System.out.println(Thread.currentThread().getName() + ": " + i++);
                } else {
                    break;
                }
                //当前线程进入阻塞状态
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

